﻿namespace Example.Structural.Facade
{
    using System;
    using System.Net;

    public static class Http
    {
        public static bool Match(this Uri uri, 
                                 string etag)
        {
            if (null == uri)
            {
                throw new ArgumentNullException("uri");
            }

            if (!uri.IsAbsoluteUri)
            {
                throw new ArgumentOutOfRangeException("uri");
            }

            if (null == etag)
            {
                throw new ArgumentNullException("etag");
            }

            bool result;

            var request = WebRequest.Create(uri.AbsoluteUri);
            request.Method = "HEAD";
            request.Headers.Add(HttpRequestHeader.IfMatch, etag);
            using (var response = GetResponse(request))
            {
                result = HttpStatusCode.OK == response.StatusCode;
            }

            return result;
        }

        private static HttpWebResponse GetResponse(WebRequest request)
        {
            HttpWebResponse result;

            try
            {
                result = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException exception)
            {
                result = (HttpWebResponse)exception.Response;
            }

            return result;
        }
    }
}